<?php

//require('open-scriptures.orm.php');
error_reporting(E_ALL);

class OpenScriptures {
	
}

class User extends OpenScriptures {
	//static private $all_records = array(
	//	array('id' => 1, 'name' => 'Weston', 'count' => '6 feet'),
	//	array('id' => 2, 'name' => 'LaVonne', 'count' => '5.3 feet'),
	//	array('id' => 3, 'name' => 'Nate', 'count' => '6 feet')
	//);
	
	private $all_records = array();
	private $records = array();
	
	#private $records = 
	
	public function __construct($id = null){
		if($id){
			for($i = 0; $i < count($this->all_records); $i++){
				if($this->all_records[$i]['id'] == $id){
					$this->records[] = &$this->all_records[$i];
					break;
				}
			}
		}
		else {
			$this->all_records = array(
				array('id' => 1, 'name' => 'Weston', 'count' => '6 feet'),
				array('id' => 2, 'name' => 'LaVonne', 'count' => '5.3 feet'),
				array('id' => 3, 'name' => 'Nate', 'count' => '6 feet')
			);
			
			foreach($this->all_records as &$record){
				$this->records[] = &$record;
			}
		}
	}
	
	public function count(){ //aka length()
		return count($this->records);
	}
	
	public function delete(){
		for($i = 0; $i < count($this->records); $i++){
			#unset($record);
			$this->records[$i] = null;
			unset($this->records[$i]);
		}
	}
	
	public function item($index){ //should this be a range?
		$count = $this->count();
		if($index < 0 || $index+1 > $count)
			throw new Exception('Out of bounds');
		if($count == 1)
			return $this;
		else {
			$that = new self();
			$that->records = array(&$this->records[$index]);
			return $that;
		}
	}
	
	public function __get($key){
		if($this->count() == 1)
			return @$this->records[0][$key];
		else
			return @array_map(create_function('$arr', "return \$arr['$key'];"), $this->records);
	}
	
	public function __set($key, $value){
		if(is_array($value)){
			$count = count($value);
			if($count != $this->count())
				throw new Exception('Array value count does not match the number of entries');
			if(!array_key_exists($key, $this->records[0]))
				throw new Exception("Property '$key' does not exist.");
			for($i = 0; $i < $count; $i++){
				$this->records[$i][$key] = $value[$i];
			}
		}
		else {
			if(!array_key_exists($key, $this->records[0]))
				throw new Exception("Property '$key' does not exist.");
			for($i = 0; $i < count($this->records); $i++){
				$this->records[$i][$key] = $value;
			}
		}
	}
	
}

echo '<pre>';

$objs = new User();
//print_r($obj->count);
//print_r($obj->count());
$obj = $objs->item(2);
print_r($objs->name);
echo $obj->name;
echo "\n\n";


#$objs->name = array('Westy', 'LaVonage', 'NTMW');
$objs->item(2)->name = 'Fro';
$obj = $objs->item(0);
$obj->name = "FREAKING WEST";

print_r($objs->name);
#echo $objs->item(3)->name;
echo "\n\n";

$objs->item(1)->delete();
print_r($objs->name);
#echo $objs->item(3)->name;
echo "\n\n";

#->name

#print_r($obj->name);

?>